package org.esky.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

import org.esky.reflect.entity.Biz;
import org.esky.reflect.entity.User;

/**
 * @author Jack.Xu
 * @ClassName: MyFieldRef
 * @Description: TODO
 * @author: Jack.Xu
 * @date: 2013年10月18日 下午1:54:18
 */
public class MyFieldRef {
	
	public static void fieldRef() throws Throwable{
		// 通过类装载器获取User类对象  
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		Class<?> clazz = loader.loadClass("org.esky.entity.User");
		
		// 获取类的默认构造器对象并通过它实例化User
		Constructor<?> constructor = clazz.getDeclaredConstructor((Class[])null);
		User user = (User) constructor.newInstance();
		
		// 取消Java语言访问检查以访问private变量 
		Field name = clazz.getDeclaredField("name");
		name.setAccessible(true);
		name.set(user, "luce");
		System.out.println(user);
		
		System.out.println("--------------------------------------------------");
		
		Class<?> c = Biz.class;
		Field xf = c.getField("x");
		Field yf = c.getField("y");

		Biz biz = new Biz();

		System.out.println("变更前x=" + xf.get(biz));
		// 变更成员x值
		xf.set(biz, 1.1);
		System.out.println("变更后x=" + xf.get(biz));
		
		System.out.println("变更前y=" + yf.get(biz));
		// 变更成员y值
		yf.set(biz, 2.1);
		System.out.println("变更后y=" + yf.get(biz));
	}
}
